package com.crazy.mybatis.gerenator.service.xml;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Component;

import com.crazy.mybatis.gerenator.service.Context;
import com.crazy.mybatis.gerenator.service.common.ElementName;

@Component
public class InsertSelectiveBuilder extends AbstractElementBuilder implements ElementBuilder {

	private static final String DEFAULT_ID = "insertSelective";

	public InsertSelectiveBuilder() {
		this(DEFAULT_ID, ElementName.INSERT);
	}

	public InsertSelectiveBuilder(String id, String elementName) {
		super(id, elementName);
	}

	@Override
	public Element build(Context context) {
		Element insert = DocumentHelper.createElement(this.elementName);
		insert.addAttribute("id", this.id);
		insert.addAttribute("parameterType", context.getAbsoluteModel());
		insert.addText(intent(2) + "INSERT INTO " + context.getTableName());

		Element trim = insert.addElement("trim");
		trim.addAttribute("prefix", "(");
		trim.addAttribute("suffix", ")");
		trim.addAttribute("suffixOverrides", ",");
		buildChildrenElement(trim, context, true);
		Element trim2 = insert.addElement("trim");
		trim2.addAttribute("prefix", "VALUES (");
		trim2.addAttribute("suffix", ")");
		trim2.addAttribute("suffixOverrides", ",");
		buildChildrenElement(trim2, context, false);
		return insert;
	}

	private void buildChildrenElement(Element trim, Context context, boolean flag) {
		for (String column : context.getColumnList()) {
			Element ifElement = trim.addElement("if");
			ifElement.addAttribute("test", context.getColumnPropertyMap().get(column) + " != null");
			if (flag) {
				ifElement.setText(intent(4) + column + ",");
			} else {
				ifElement.setText(new StringBuilder(intent(4))
					.append("#{")
					.append(context.getColumnPropertyMap().get(column))
					.append(", jdbcType=")
					.append(context.getColumnJdbcTypeMap().get(column))
					.append("},").toString());
			}
		}
	}
}
